package com.swpu.cbg.cnshop.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.squareup.okhttp.Response;
import com.swpu.cbg.cnshop.Constans;
import com.swpu.cbg.cnshop.R;
import com.swpu.cbg.cnshop.bean.Favorites;
import com.swpu.cbg.cnshop.bean.User;
import com.swpu.cbg.cnshop.bean.Ware;
import com.swpu.cbg.cnshop.http.OkHttpHelper;
import com.swpu.cbg.cnshop.http.SpotsCallback;
import com.swpu.cbg.cnshop.utils.CartProvider;
import com.swpu.cbg.cnshop.utils.ToastUtil;
import com.swpu.cbg.cnshop.widget.cnToolbar;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import cn.sharesdk.framework.ShareSDK;
//import cn.sharesdk.onekeyshare.OnekeyShare;
import dmax.dialog.SpotsDialog;

/**
 * Created by chenboge on 16/2/16.
 */
public class WareDetilActivity extends BaseActivity {

    @ViewInject(R.id.id_ware_detil_webview)
    private WebView mWebView;

    @ViewInject(R.id.toolbar)
    private cnToolbar mToolbar;

    private Ware mWare;

    private SpotsDialog mDialog;

    private CartProvider mProvider;

    private WebAppInterface mInterface;

    private OkHttpHelper mHelper = OkHttpHelper.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ware_detil);
        ViewUtils.inject(this);
        Serializable serializable = getIntent().getSerializableExtra(Constans.API.TAG_WARE);
        if (serializable == null)
            this.finish();

        mWare = (Ware) serializable;

        mProvider = new CartProvider(this);
        mDialog = new SpotsDialog(this, "loading....");
        mDialog.show();
        initToolbar();
        initWebView();
    }

    private void initToolbar() {
        mToolbar.hideRightButton();
        mToolbar.hideContent();
        mToolbar.showEditButton();
        mToolbar.showTitle();
        mToolbar.setEditButtonText("分享");
        mToolbar.getmEditButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // showShare();
            }
        });
    }

//
//    private void showShare() {
//        ShareSDK.initSDK(this);
//        OnekeyShare oks = new OnekeyShare();
//        //关闭sso授权
//        oks.disableSSOWhenAuthorize();
//
//// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
//        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
//        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
//        oks.setTitle(getString(R.string.share));
//        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
//        oks.setTitleUrl("http://sharesdk.cn");
//        // text是分享文本，所有平台都需要这个字段
//        oks.setText(mWare.getName());
//        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
//        oks.setImageUrl(mWare.getImgUrl());
//        // url仅在微信（包括好友和朋友圈）中使用
//        oks.setUrl("http://sharesdk.cn");
//        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment(mWare.getName());
//        // site是分享此内容的网站名称，仅在QQ空间使用
//        oks.setSite(getString(R.string.app_name));
//        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
//        oks.setSiteUrl("http:gitos.china/chenbaige");
//
//// 启动分享GUI
//        oks.show(this);
//    }

//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        ShareSDK.stopSDK(this);
//    }

    private void initWebView() {
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAppCacheEnabled(true);
        settings.setBlockNetworkImage(false);
        mInterface = new WebAppInterface();
        mWebView.loadUrl(Constans.API.WARE_DETAIL);
        mWebView.addJavascriptInterface(mInterface, "appInterface");
        mWebView.setWebViewClient(new WC());
    }


    class WebAppInterface {

        @JavascriptInterface
        public void showDetail() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mWebView.loadUrl("javascript:showDetail(" + mWare.getId() + ")");
                }
            });
        }

        @JavascriptInterface
        public void buy(long id) {
            mProvider.put(mWare);
            ToastUtil.showToast(WareDetilActivity.this, "商品已经添加至购物车");
        }

        @JavascriptInterface
        public void addFavorites(long id) {

            User user = MyApplication.getInstanse().getUser();

            if (user == null) {
                startActivity(new Intent(WareDetilActivity.this, LoginActivity.class), true);
            }


            Long userId = user.getId();

            HashMap<String, Object> params = new HashMap<>();
            params.put("user_id", userId);
            params.put("ware_id", mWare.getId());


            mHelper.post(Constans.API.FAVORITE_CREATE, params, new SpotsCallback<List<Favorites>>(WareDetilActivity.this) {
                @Override
                public void onSuccess(Response response, List<Favorites> favorites) {
                    ToastUtil.showToast(WareDetilActivity.this, "已添加到收藏夹");
                }

                @Override
                public void onError(Response response, int code, Exception e) {

                    LogUtils.d("code:" + code);
                }

                @Override
                public void onTokenError(Response response, int code) {

                }
            });


        }

    }


    class WC extends WebViewClient {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
            }
            mInterface.showDetail();
        }
    }

}


